package ucuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginNoAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginNoAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginNoAuthLogic {
	return &LoginNoAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 无需验证登陆
func (l *LoginNoAuthLogic) LoginNoAuth(in *pb.LoginUserNoAuthReq) (*pb.LoginUserResp, error) {
	defer utils.RecoverPanic()

	var err error
	var userAcc *usercenter.UserAccount
	userAcc, err = l.svcCtx.UserAccountModel.FindOne(l.ctx, in.Uid)
	if err != nil {
		if err == usercenter.ErrNotFound {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "user not found")
		}
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	userAcc.AppsFlyerUid = in.AppsFlyerUID
	// 登陆时，更新appsFlyeruid
	err = l.svcCtx.UserAccountModel.Update(l.ctx, userAcc)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	l2 := NewLoginLogic(l.ctx, l.svcCtx)
	return l2.noAuthLogin(in, userAcc)
}
